package filter;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class FindLines {
	public static BufferedImage stroke3(BufferedImage img) {
		BufferedImage newImg = new BufferedImage(img.getWidth(),
				img.getHeight(), img.getType());
		int WHITE = Color.WHITE.getRGB();
		int w = img.getWidth();
		int h = img.getHeight();
		Graphics2D gd2 = (Graphics2D) newImg.getGraphics();
		gd2.setStroke(new BasicStroke(3));

		for (int y = 0; y < h; y++) {
			for (int x = 0; x < w; x++) {
				if (img.getRGB(x, y) == WHITE) {
					gd2.drawLine(x, y, x, y);
				}
			}
		}
		return newImg;
	}

	public static BufferedImage find(BufferedImage img) {
		BufferedImage newImg = new BufferedImage(img.getWidth(),
				img.getHeight(), img.getType());
		int w = img.getWidth();
		int h = img.getHeight();
		int whm = Math.max(w, h);
		double halfPI = Math.PI;
		int WHITE = Color.WHITE.getRGB();
		double d = 90d;
		int n = 0;
		Graphics2D gd2 = (Graphics2D) img.getGraphics();

		for (int y = 0; y < h; y++) {
			for (int x = 0; x < w; x++) {
				if (img.getRGB(x, y) == WHITE) {
					int x1 = x;
					int y1 = y;
					int maxx = x;
					int maxy = y;
					double maxz = 20;
					for (double a = 0; a < d; a++) {
						for (double z = 1; z < whm; z++) {
							int x2 = (int) (x1 + (z * Math
									.cos(halfPI * (a / d))));
							int y2 = (int) (y1 + (z * Math
									.sin(halfPI * (a / d))));
							// System.out.println(x2 + "," + y2);
							// newImg.setRGB(x2, y2, 255);
							if (x2 < w && y2 < h && img.getRGB(x2, y2) == WHITE) {
								if (z > maxz) {
									maxx = x2;
									maxy = y2;
									maxz = z;
								}
							} else {
								break;
							}
						}
					}
					
					if (maxz != 20) {
						newImg.getGraphics().drawLine(x1, y1, maxx, maxy);
						n++;
					}
				}
			}
		}

		System.out.println(n);

		return newImg;
	}

	public static void main(String[] args) throws IOException {
		BufferedImage img = ImageIO.read(NewSobel.class
				.getResource("/resource/letters.png"));
		img = NewSobel.applyThreshold(NewSobel.apply(img), 10);
		img = stroke3(img);

		ImageIO.write(find(img), "png", new File("shape.png"));
		ImageIO.write(img, "png", new File("sobel1.png"));
	}
}
